/*
 * @Author: xiaosihan 
 * @Date: 2022-05-08 14:25:26 
 * @Last Modified by: 肖思汗
 * @Last Modified time: 2025-08-Mo 07:04:17
 */

import boxen from 'boxen';
import dotenv from 'dotenv';
import killPort from 'kill-port';
// 加载对应环境的env文件
if (process.env.NODE_ENV?.trim() === "development") {
    dotenv.config({ path: '.env', quiet: true });
}

// 打印出所有环境变量
console.log("NODE_ENV", process.env.NODE_ENV);
console.log("DB_NAME", process.env.DB_NAME);
console.log("DB_USER", process.env.DB_USER);
console.log("DB_PASSWORD", process.env.DB_PASSWORD);
console.log("DB_HOST", process.env.DB_HOST);
console.log("DB_PORT", process.env.DB_PORT);
console.log("BUILD_TIME", process.env.BUILD_TIME);
console.log("NODE_ENV", process.env.NODE_ENV);
console.log("accessKeyId", process.env.accessKeyId);
console.log("accessKeySecret", process.env.accessKeySecret);
console.log("oss_host", process.env.oss_host);


// 创建简化的utils对象，避免导入完整的utils模块（包含微信小程序API）
const utils = {
    // 只包含服务端需要的基本方法
    isDev: process.env.NODE_ENV?.trim() === "development",
    isTest: process.env.NODE_ENV?.trim() === "test",
    isProd: process.env.NODE_ENV?.trim() === "production",
    // 其他服务端可能需要的方法可以在这里添加
};

import cors from "cors";
import express from "express";
import morgan from 'morgan';

import dayjs from "dayjs";
import timezone from 'dayjs/plugin/timezone';
import utc from 'dayjs/plugin/utc';
import CadConversionService from './services/cadConversionService';
import DataService from './services/DataService';
import FabricService from './services/fabricService';
import MyImgService from './services/myImgService';
import MySQLService from './services/mysqlEventService';
import OSSService from './services/ossService';
import RenderService from './services/renderService';
import SystemService from './services/systemService';
import UserService from './services/userService';
import utilsService from './services/utilsService';

// 创建各个服务的实例
const userService = new UserService();
const cadConversionService = new CadConversionService();
const dataService = new DataService();
const myImgService = new MyImgService();
const mySQLService = new MySQLService();
const fabricService = new FabricService();
const ossService = new OSSService();
const renderService = new RenderService();
const systemService = new SystemService();

dayjs.extend(utc);
dayjs.extend(timezone);

const app = express();

// app.use(cookieParser());
app.use(morgan('dev')); // 打印请求日志
app.use(express.json({ limit: '1024mb' }));
app.use(express.urlencoded({ limit: '1024mb', extended: true }));
app.use(cors()); // 设置跨域

// 添加控制浏览器不缓存本地请求的中间件
app.use((req: express.Request, res: express.Response, next: express.NextFunction) => {
    // 设置不缓存的响应头
    // Cache-Control: 现代浏览器缓存控制的主要指令
    // - no-store: 禁止浏览器和代理服务器存储任何版本的响应
    // - no-cache: 浏览器可以存储响应，但在使用前必须先向服务器验证
    // - must-revalidate: 过期后必须向服务器验证
    // - proxy-revalidate: 要求共享缓存（如代理服务器）必须验证过期资源
    res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate');
    // Pragma: HTTP/1.0兼容的缓存控制指令，与Cache-Control: no-cache效果相同
    res.setHeader('Pragma', 'no-cache');
    // Expires: 设置响应的过期时间为0，即立即过期
    res.setHeader('Expires', '0');
    // Surrogate-Control: 针对CDN等代理服务器的缓存控制指令
    res.setHeader('Surrogate-Control', 'no-store');
    next();
});

// 服务基类会自动将所有公共方法注册为POST路由
// 使用实例方法注册各个服务（提供更大的灵活性）
userService.register(app);
cadConversionService.register(app);
dataService.register(app);
myImgService.register(app);
mySQLService.register(app);
fabricService.register(app);
ossService.register(app);
renderService.register(app);
systemService.register(app);
utilsService.register(app);


app.use((req: express.Request, res: express.Response, next: express.NextFunction) => {
    res.status(404).send('很抱歉,没有找到请求地址_');
})

let port = 8081; // 端口

// 在服务启动前清理端口
killPort(port).then(() => {
    app.listen(port, () => {
        const startTime = dayjs().tz('Asia/Shanghai').format("YYYY-MM-DD HH:mm:ss");
        const boxenContent = `
服务正在运行在端口 ${port}
启动时间: ${startTime}
`.trim();
        // 使用boxen打印美化的启动信息
        console.log(boxen(boxenContent, {
            padding: 0.5,
            margin: 0.2,
            borderStyle: 'round',
            borderColor: 'green',
        }));
    });
});
